<?php

namespace Admin\Model;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Select;


class BangdiemTable extends AbstractTableGateway {

    protected $table = 'bangdiem';

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
        $this->resultSetPrototype->setArrayObjectPrototype(new Bangdiem());

        $this->initialize();
    }

    public function fetchAll(Select $select = null) {
        if (null === $select)
            $select = new Select();
        $select->from($this->table,array('*'))
				->join(
					'hocsinh',
					'hocsinh.id = bangdiem.hocsinh',
					array('tenhs'))
				->join(
					'monhoc',
					'monhoc.id = bangdiem.monhoc',
					array('tenmonhoc'))
				->join(
					'loaidiem',
					'loaidiem.id = bangdiem.loaidiem',
					array('tenloaidiem'));
        $resultSet = $this->selectWith($select);
        $resultSet->buffer();
        return $resultSet;
    }

    public function getBangdiem($id) {
        $id = (int) $id;
        $rowset = $this->select(array('id' => $id));
        $row = $rowset->current(); 
        return $row;
    }

    public function saveBangdiem(Bangdiem $bangdiem) {
		
			
		
        

        $id = (int) $bangdiem->id;
        if ($id == 0) {
			$data = array(
				'hocsinh' => $bangdiem->hocsinh,
				'monhoc' => $bangdiem->monhoc,
				'sodiem' => $bangdiem->sodiem,
				'namhoc' => $bangdiem->namhoc,
				'hocki' => $bangdiem->hocki,
				'loaidiem' => $bangdiem->loaidiem,
				
			);
            	
                $this->insert($data);
            
        } else {
			
			$data = array(
				'hocsinh' => $bangdiem->hocsinh,
				'monhoc' => $bangdiem->monhoc,
				'sodiem' => $bangdiem->sodiem,
				'namhoc' => $bangdiem->namhoc,
				'hocki' => $bangdiem->hocki,
				'loaidiem' => $bangdiem->loaidiem,
			);
            if ($this->getBangdiem($id)) {
				
					$this->update($data, array('id' => $id));
				
            } else {
                throw new \Exception('Không tồn tại');
            }
        }
    }

    public function deleteBangdiem($id) {
        $this->delete(array('id' => $id));
    }
	public function xoaBangdiem($id) {
		
        $this->delete('id IN (' . $id . ')');
    }
	
	//kiem tra ton tai
	public function check_exists($monhoc,$hocsinh,$namhoc,$hocki,$id)
	{
		//$rowset = $this->select(array('title' => $title));
        //$row = $rowset->current();
		$resultSet = $this->select(array('monhoc = "'.$monhoc.'"','hocsinh = "'.$hocsinh.'"','namhoc = "'.$namhoc.'"','hocki = "'.$hocki.'"', 'id != "'.$id.'"'));
    	$row = $resultSet->current();
        return $row;
		
	}
	


}
